package com.yicheng.statistics.actor

import com.yicheng.statistics.repo.cassandra.DataInfoDB
import com.yicheng.statistics.common.TimeUtils
import com.yicheng.statistics.repo.model.Data.DataInfo
import scala.util.Failure
import scala.util.Success
import scala.util.control.Exception.Catch

trait AnalysisParser{
  
  import scala.concurrent.ExecutionContext.Implicits.global
  
  /**
   * 获得设备一整天的数据
   */
  def parseOneDayDataInfo[T](deviceType:Int, deviceId:String , t:T, func: (T, Seq[DataInfo], Boolean) => T) : Unit = {
  
    /**
     * start 开始时间 1(一点)
     * interval 时间步长
     */
    def getHourData(start:Int, interval:Int, t:T): Unit = {
      val time = TimeUtils.getStartEndTimeByHour(start, 1)//取开始时间和结束时间(前一天)
      if(start != 23) {
        DataInfoDB.list(deviceType, deviceId, time._1.toDate(), time._2.toDate()) onComplete {
          case Success(result) =>
            val r = func(t, result, false)
            getHourData(start + 1, interval, r)
          case Failure(error) =>
            println("查询数据失败"+error)
        }
      }else{
        
        DataInfoDB.list(deviceType, deviceId, time._1.toDate(), time._2.toDate()) onComplete {
          case Success(result) =>
            func(t,result, true)//最后一一次处理结束
          case Failure(error) =>
            println("查询数据失败"+error)
        }
      }
    }
    
    getHourData(0, 1, t)
  }
  
  type S
  /**
   * t 上一次计算的结果
   * s 分析设置的条件 
   */
  def parseOneDayDataInfo[T](deviceType:Int, deviceId:String , t:T, s:S, func: (T, S, Seq[DataInfo], Boolean) => T) : Unit = {
    /**
     * start 开始时间 1(一点)
     * interval 时间步长
     */
    def getHourData(start:Int, interval:Int, t:T, s:S): Unit = {
      val time = TimeUtils.getStartEndTimeByHour(start, 1)//取开始时间和结束时间(前一天)
      println("time now is"+start)
      if(start != 23) {
        DataInfoDB.list(deviceType, deviceId, time._1.toDate(), time._2.toDate()) onComplete {
          case Success(result) =>
            val r = func(t, s, result, false)
            try{
              getHourData(start + 1, interval, r, s)
            }catch{
              case ex:Exception => println(ex.getMessage)
            }
            
          case Failure(error) =>
            println("查询数据失败"+error)
        }
      }else{
        
        DataInfoDB.list(deviceType, deviceId, time._1.toDate(), time._2.toDate()) onComplete {
          case Success(result) =>
            func(t, s, result, true)
          case Failure(error) =>
            println("查询数据失败"+error)
        }
      }
    }
    
    getHourData(0, 1, t, s)
  }
}